import "../lib/jquery.js";
import axios from "../lib/axios.js";

$(function () {
  const authorization = localStorage.getItem("authorization");
  let user = JSON.parse(localStorage.getItem("user"));

  if (authorization && user) {
    // 获取用户信息
    axios
      .get("http://localhost:9000/users/info", {
        params: {
          id: user.id,
        },
        headers: {
          authorization: authorization,
        },
      })
      .then(({ data }) => {
        if (data.code === 1) {
          user = data.user; // 更新user对象
          populateUserForm(user);
        } else {
          handleUnauthorizedAccess(data.message);
        }
      })
      .catch(error => {
        console.error("Error fetching user info:", error);
        alert("无法获取用户信息，请稍后再试。");
      });
  } else {
    redirectToLogin();
  }

  // 表单提交事件处理
  $("form").submit(function (e) {
    e.preventDefault();
    updateUserProfile(user.id, authorization);
  });

  // 填充表单数据的函数
  function populateUserForm(user) {
    $("input.username").val(user.username);
    $("input.age").val(user.age);
    $("select.gender").val(user.gender);
    $("input.nickname").val(user.nickname);
  }

  // 更新用户资料的函数
  function updateUserProfile(userId, token) {
    const formData = { id: userId };
    $("form input, form select").each(function () {
      formData[$(this).attr("class")] = $(this).val();
    });

    axios
      .post("http://localhost:9000/users/update", formData, {
        headers: {
          authorization: token,
        },
      })
      .then(({ data }) => {
        alert(data.message);
      })
      .catch(error => {
        console.error("Error updating user profile:", error);
        alert("更新失败，请稍后再试。");
      });
  }

  // 处理未授权访问的函数
  function handleUnauthorizedAccess(message) {
    localStorage.removeItem("authorization");
    localStorage.removeItem("user");
    alert(message);
    redirectToLogin();
  }

  // 重定向到登录页面的函数
  function redirectToLogin() {
    location.href = "login.html";
  }
});
